package com.qiantu.phone.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;

import java.math.BigDecimal;

/**
 * @ClassName RoundSeekBar
 * @Description TODO
 * @Author ShiJunqiang
 * @Date 2021/5/21 16:54
 * @Version 1.0
 */
public class FloorHeatingSeekBar extends View {
    /**
     * 圆环笔画的宽度
     */
    private float mStrokeWidth;
    private static final int LINE_START_DEGREES = 36;
    private static final int CALCULATE_START_DEGREES = 54;
    private static final int START_DEGREES = 126;
    private static final int TOTAL_DEGREES = 288;
    //无极的进度
    private float mProgress;
    //不进进度，不是无极的进度
    private float mPerIntervalProgress;
    private float mTemp;
    //默认温度
    private int defaultTemp = 26;
    private Drawable centerOnDrawable;
    private Drawable centerOffDrawable;
    private Drawable smallBackgroundDrawable;
    private Drawable bigBackgroundDrawable;
    private RectF arcRectF;
    private int barRadius;
    private int barStrokeWidth;
    private SweepGradient mGradient;
    private Paint mPaint;
    private TextPaint mTextPaint;
    private int closeTextSize;
    private int percentageTextSize;
    private int unitAndLabelTextSize;
    private String labelText;
    private String unitText = "°C";
    private int percentage_label_padding;
    private boolean isOpen = false;

    private int[] gradientColors = new int[]{0xffFFC970, 0xffFB934E, AppApplication.getInstance().getThemeColor(R.attr.secondaryColor1), 0xffFE3F3B};
    private float[] gradientPositions = new float[]{0, 0.5f, 0.75f, 1};
    private Matrix matrix;
    private float max = 34;
    private float min = 5;
    private float tempTotalInterval;
    //是否1单位递增
    private boolean isOneInterval = true;
    //圆弧区域内down
    private boolean isInArcDown;
    //圆环区域内down
    private boolean isInRingDown;
    //开关范围
    private Rect switchRect;
    private int switchClickPadding;
    private boolean isSwitchDown;
    private double mLastDegrees = -1;
    private double mCurrentDegrees;
    //拖拽是否继续更改进度环
    private boolean dragFlag = true;
    //有没有move进圆弧内
    private boolean hasMoveInArc;
    //温度是否设置
    private boolean tempIsNotSet;
    private float arcPadding;
    private float rotationDegree;
    private String openText;
    private String closeText;
    private boolean isSelectActionMode;
    private float centerRadius;
    private int deviceSolidBgColor;

    public FloorHeatingSeekBar(Context context) {
        this(context, null);
    }

    public FloorHeatingSeekBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FloorHeatingSeekBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public FloorHeatingSeekBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mStrokeWidth = getResources().getDimensionPixelSize(R.dimen.dp_18);
        centerOnDrawable = AppApplication.getInstance().getThemeDrawable(R.attr.icon_devicecontrol_curtain_switch_4);
        centerOffDrawable = AppApplication.getInstance().getThemeDrawable(R.attr.icon_devicecontrol_curtain_switch_2);
        smallBackgroundDrawable = AppApplication.getInstance().getThemeDrawable(R.attr.icon_devicecontrol_heatingfloor);
        bigBackgroundDrawable = AppApplication.getInstance().getThemeDrawable(R.attr.icon_devicecontrol_heatingfloor_bgcolor);
        arcRectF = new RectF();
        barRadius = getResources().getDimensionPixelSize(R.dimen.dp_14);
        barStrokeWidth = getResources().getDimensionPixelSize(R.dimen.dp_1);
        closeTextSize = getResources().getDimensionPixelSize(R.dimen.dp_20);
        percentageTextSize = getResources().getDimensionPixelSize(R.dimen.dp_24);
        unitAndLabelTextSize = getResources().getDimensionPixelSize(R.dimen.dp_12);
        percentage_label_padding = getResources().getDimensionPixelSize(R.dimen.dp_8);
        arcPadding = getResources().getDimensionPixelSize(R.dimen.dp_40);
        matrix = new Matrix();
        switchRect = new Rect();
        switchClickPadding = getResources().getDimensionPixelSize(R.dimen.dp_10);
        openText = getResources().getString(R.string.heating_up);
        closeText = getResources().getString(R.string.close);
        deviceSolidBgColor = AppApplication.getInstance().getThemeColor(R.attr.deviceSolidBgColor);
        initOutDegreeScale();
    }

    public void setMinMax(float min, float max) {
        this.min = min;
        this.max = max;
        initOutDegreeScale();
        invalidate();
    }

    private void initOutDegreeScale(){
        tempTotalInterval = (max - min);
//        leftValue = (int)((tempTotalInterval * CALCULATE_START_DEGREES / Float.valueOf(TOTAL_DEGREES)) + min);
//        topValue = (int)((tempTotalInterval * (CALCULATE_START_DEGREES + 90) / Float.valueOf(TOTAL_DEGREES)) + min);
//        rightValue = (int)((tempTotalInterval * (CALCULATE_START_DEGREES + 180) / Float.valueOf(TOTAL_DEGREES)) + min);
//        leftText = leftValue + unitText;
//        topText = topValue + unitText;
//        rightText = rightValue + unitText;
    }

    public void setDefaultTemp(int defaultTemp) {
        this.defaultTemp = defaultTemp;
    }

    public void isOneInterval(boolean isOneInterval) {
        this.isOneInterval = isOneInterval;
    }

    public void isSelectActionMode(boolean isSelectActionMode) {
        this.isSelectActionMode = isSelectActionMode;
        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int defaultValue = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics());
        int width = measureHandler(widthMeasureSpec, defaultValue);
        int height = measureHandler(heightMeasureSpec, defaultValue);
        setMeasuredDimension(Math.min(width, height), Math.min(width, height));
    }

    /**
     * 测量
     *
     * @param measureSpec
     * @param defaultSize
     * @return
     */
    private int measureHandler(int measureSpec, int defaultSize) {
        int result = defaultSize;
        int measureMode = MeasureSpec.getMode(measureSpec);
        int measureSize = MeasureSpec.getSize(measureSpec);
        if (measureMode == MeasureSpec.EXACTLY) {
            result = measureSize;
        } else if (measureMode == MeasureSpec.AT_MOST) {
            result = Math.min(defaultSize, measureSize);
        }
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawArc(canvas);
    }

    private void drawArc(Canvas canvas) {
        int width = getWidth();
        int height = getHeight();
        int centerX = width / 2;
        int centerY = height / 2;
        int radius = Math.min(centerX, centerY);


        bigBackgroundDrawable.setBounds(0, 0, width, height);
        bigBackgroundDrawable.draw(canvas);

        mTextPaint.setTypeface(Typeface.DEFAULT);

        arcRectF.left = mStrokeWidth / 2 + arcPadding;
        arcRectF.top = centerY - radius + mStrokeWidth / 2 + arcPadding;
        arcRectF.right = width - mStrokeWidth / 2 - arcPadding;
        arcRectF.bottom = centerY + radius - mStrokeWidth / 2 - arcPadding;

        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(deviceSolidBgColor);
        mPaint.setShadowLayer(getResources().getDimensionPixelSize(R.dimen.dp_24), 0, getResources().getDimensionPixelSize(R.dimen.dp_10), 0xfffed2bc);
        canvas.drawCircle(centerX, centerY, radius - mStrokeWidth - arcPadding, mPaint);
        mPaint.setShadowLayer(getResources().getDimensionPixelSize(R.dimen.dp_13), 0, getResources().getDimensionPixelSize(R.dimen.dp_4), 0x0525334b);
        centerRadius = radius - mStrokeWidth - arcPadding;
        canvas.drawCircle(centerX, centerY, centerRadius, mPaint);
        mPaint.clearShadowLayer();
        mTextPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor6));

        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(mStrokeWidth);
        mPaint.setColor(0xfffcd8c7);
        canvas.drawArc(arcRectF, START_DEGREES, TOTAL_DEGREES, false, mPaint);

        int bottom = (int) (centerY + radius - getResources().getDimensionPixelSize(R.dimen.dp_16) - arcPadding - mStrokeWidth);
        switchRect.bottom = bottom;
        Paint.FontMetricsInt fontMetricsInt = null;
        if (!isOpen) {//关闭状态
            stop();
            //选择设备动作模式
            if(isSelectActionMode) {
                labelText = "";
            }else {
                labelText = closeText;
            }
            rotationDegree = 0;
            canvas.save();
            smallBackgroundDrawable.setBounds(0, 0, width, height);
            smallBackgroundDrawable.draw(canvas);
            canvas.restore();

            mTextPaint.setTextSize(closeTextSize);
            mTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
            if (centerOffDrawable != null) {
                switchRect.left = radius - centerOffDrawable.getIntrinsicWidth() / 2;
                switchRect.top = bottom - centerOffDrawable.getIntrinsicHeight();
                switchRect.right = radius + centerOffDrawable.getIntrinsicWidth() / 2;
                switchRect.bottom = bottom;
                centerOffDrawable.setBounds(switchRect);
                centerOffDrawable.draw(canvas);
            }
        } else {

            smallBackgroundDrawable.setBounds(0, 0, width, height);
            //选择设备动作模式
            if(isSelectActionMode) {
                labelText = "";
                smallBackgroundDrawable.draw(canvas);
            }else{
                labelText = openText;
                start();
                canvas.save();
                canvas.rotate(rotationDegree, centerX, centerY);
                smallBackgroundDrawable.draw(canvas);
                canvas.restore();
            }
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(mStrokeWidth);
            if (mGradient == null) {
                mGradient = new SweepGradient(centerX, centerY, gradientColors, gradientPositions);
                matrix.setRotate(CALCULATE_START_DEGREES, centerX, centerX);
                mGradient.setLocalMatrix(matrix);
            }
            mPaint.setShader(mGradient);
            float currentDegrees = mPerIntervalProgress * TOTAL_DEGREES;
            canvas.drawArc(arcRectF, START_DEGREES, currentDegrees, false, mPaint);
            mPaint.setShader(null);

            int barCenterToCenter = (int) (radius - arcPadding - mStrokeWidth / 2);
            int barCenterX = (int) (centerX - (Math.cos((currentDegrees - CALCULATE_START_DEGREES) * Math.PI / 180) * barCenterToCenter));
            int barCenterY = (int) (centerY - (Math.sin((currentDegrees - CALCULATE_START_DEGREES) * Math.PI / 180) * barCenterToCenter));
            mPaint.setColor(0xffffffff);
            mPaint.setStyle(Paint.Style.FILL);
            canvas.drawCircle(barCenterX, barCenterY, barRadius, mPaint);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(barStrokeWidth);
            mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor4));
            canvas.drawCircle(barCenterX, barCenterY, barRadius - barStrokeWidth / 2, mPaint);
            if (centerOnDrawable != null) {
                switchRect.left = radius - centerOnDrawable.getIntrinsicWidth() / 2;
                switchRect.top = bottom - centerOnDrawable.getIntrinsicHeight();
                switchRect.right = radius + centerOnDrawable.getIntrinsicWidth() / 2;
                switchRect.bottom = bottom;
                centerOnDrawable.setBounds(switchRect);
                centerOnDrawable.draw(canvas);
            }
        }

        String text;
        int textSize = 0;
        if(tempIsNotSet){
            text = getResources().getString(R.string.not_set);
            textSize = closeTextSize;
        }else{
            if(isSelectActionMode && !isOpen){
                text = closeText;
                textSize = closeTextSize;
            }else{
                if (mTemp * 10 % 10 == 0) {
                    text = (int) mTemp + unitText;
                } else {
                    text = mTemp + unitText;
                }
                textSize = percentageTextSize;
            }
        }
        mTextPaint.setTextSize(textSize);
        mTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
        float percentageTextWidth = mTextPaint.measureText(text);
        Paint.FontMetricsInt percentageTexFontMetricsInt = mTextPaint.getFontMetricsInt();
        int percentageTextHeight = percentageTexFontMetricsInt.descent - percentageTexFontMetricsInt.ascent;
        float percentageTextY = centerY + percentageTextHeight / 2 - percentageTexFontMetricsInt.descent;
        float percentageX = centerX - percentageTextWidth / 2;
        mTextPaint.setTextSize(textSize);
        canvas.drawText(text, percentageX, percentageTextY, mTextPaint);

        if(!TextUtils.isEmpty(labelText)){
            mTextPaint.setTextSize(unitAndLabelTextSize);
            mTextPaint.setTypeface(Typeface.DEFAULT);
            float labelTextWidth = mTextPaint.measureText(labelText);
//            float unitTextWidth = mTextPaint.measureText(unitText);
            fontMetricsInt = mTextPaint.getFontMetricsInt();
            int unitAndLabelTextHeight = fontMetricsInt.descent - fontMetricsInt.ascent;
            float labelTextY = centerY + unitAndLabelTextHeight / 2 - fontMetricsInt.descent - (percentage_label_padding + percentageTextHeight / 2);
//            float unitTextY = centerY + unitAndLabelTextHeight / 2 - fontMetricsInt.descent + (percentageTextHeight - unitAndLabelTextHeight) / 4;
            canvas.drawText(labelText, centerX - labelTextWidth / 2, labelTextY, mTextPaint);
//            canvas.drawText(unitText, percentageX + percentageTextWidth + percentage_unit_padding, unitTextY, mTextPaint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (isEnabled()) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    float downX = event.getX();
                    float downY = event.getY();
                    //按下时候进度一点一点的移动
//                    mLastDegrees = getTouchAngle(downX, downY);
                    if (isInRingArea(downX, downY)) {
                        isInRingDown = true;
                        isInArcDown = isInArcArea(downX, downY);
                    } else {
                        isInRingDown = false;
                        isInArcDown = false;
                        //开关点击范围
                        isSwitchDown = isInSwitchArea(downX, downY);
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    //开关down、关闭状态不触发滑动进度
                    if(!isInRingDown || !isOpen){
                        return true;
                    }
                    getParent().requestDisallowInterceptTouchEvent(true);
                    float moveX = event.getX();
                    float moveY = event.getY();
                    /*计算角度*/
                    double moveDegrees = getTouchAngle(moveX, moveY);
                    if(mLastDegrees == -1){
                        if(isInArcArea(moveX, moveY)){
                            mCurrentDegrees = moveDegrees;
                            mLastDegrees = moveDegrees;
                            hasMoveInArc = true;
                        }else{
                            hasMoveInArc = false;
                            return true;
                        }
                    }else{
                        calculateDegrees(moveDegrees);
                    }
                    /*计算角度*/
                    //通过角度计算百分比
                    calculateProgress();
                    //通过百分比计算温度
                    calculateTempWithTempPerInterval();
                    if (mOnChangeListener != null) {
                        mOnChangeListener.onValueChanged(mTemp);
                    }
                    tempIsNotSet = false;//已设置温度
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    float upX = event.getX();
                    float upY = event.getY();
                    //down在圆环里，并且开状态
                    if(isInRingDown && isOpen){
                        //点击圆弧内，就用up坐标重新计算最后一次百分比，并回调
                        if (isInArcDown && isInArcArea(upX, upY) && dragFlag) {
                            //计算角度
                            mCurrentDegrees = getTouchAngle(upX, upY);
                            //通过角度计算百分比
                            calculateProgress();
                            //通过百分比计算温度
                            calculateTemp();
                            tempIsNotSet = false;//已设置温度
                            if (mOnChangeListener != null) {
                                playSoundEffect(SoundEffectConstants.CLICK);
                                mOnChangeListener.onStopTrackingTouch(mTemp);
                            }
                            invalidate();
                        }else{//up不在圆弧区域内，但是move到圆弧内过，就直接回调move最后一次百分比
                            if (hasMoveInArc && mOnChangeListener != null) {
                                playSoundEffect(SoundEffectConstants.CLICK);
                                mOnChangeListener.onStopTrackingTouch(mTemp);
                            }
                        }
                    }else{
                        //点击开关按钮
                        if (isSwitchDown && isInSwitchArea(upX, upY)) {
                            isOpen = !isOpen;
                            //如果打开，并且温度是0，那么就设置默认温度
                            if(isOpen && mTemp == 0){
                                mTemp = defaultTemp;
                            }
                            tempIsNotSet = false;//已设置温度
                            calculateProgressByTemp();
                            invalidate();
                            if (mOnChangeListener != null) {
                                playSoundEffect(SoundEffectConstants.CLICK);
                                mOnChangeListener.onSwitch(isOpen);
                            }
                        }
                    }
                    isSwitchDown = false;
                    isInArcDown = false;
                    dragFlag = true;
                    hasMoveInArc = false;
                    mLastDegrees = -1;
                    break;
                case MotionEvent.ACTION_CANCEL:
                    isSwitchDown = false;
                    isInArcDown = false;
                    dragFlag = true;
                    hasMoveInArc = false;
                    mLastDegrees = -1;
                    break;
            }
        }
        return true;
    }


    //计算温度值（根据步进）
    private void calculateTempWithTempPerInterval() {
        BigDecimal bigDecimal = new BigDecimal(mProgress * tempTotalInterval + min);
        Log.i("lzx", "bigDecimal:" + bigDecimal.floatValue());
        if(isOneInterval) {
            float temp = bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP).floatValue();
            String[] tempArray = String.valueOf(temp).split("\\.");
            if (tempArray.length == 1 || "0".equals(tempArray[1])) {
                mTemp = temp;
            }
            //放到外面无极滑动，放到if里面步进滑动
            mPerIntervalProgress = mProgress;
        }else{
            float temp = bigDecimal.setScale(1, BigDecimal.ROUND_DOWN).floatValue();
            String[] tempArray = String.valueOf(temp).split("\\.");
            Log.i("lzx", "temp:" + temp);
            //整数或者小数点为5
            if ((tempArray.length == 1 || "0".equals(tempArray[1]))
                    || (tempArray.length == 2 && "5".equals(tempArray[1]))) {
                mTemp = temp;
            }
            //放到外面无极滑动，放到if里面步进滑动
            mPerIntervalProgress = mProgress;
        }
    }

    //计算温度值（无极）
    private void calculateTemp() {
        mPerIntervalProgress = mProgress;
        mTemp = (int) (mProgress * tempTotalInterval) + min;
    }

    private void calculateDegrees(double moveDegrees){
        Log.i("lzx", "moveDegrees:" + moveDegrees);
        double changeDegrees = 0;
        if(dragFlag){
            changeDegrees = moveDegrees - mLastDegrees;
            mCurrentDegrees += changeDegrees;
            //一次移动角度超过300，就是滑动到了结束和开始的边界（顺时针）
            if (mLastDegrees - moveDegrees > 300){
                dragFlag = false;
                mCurrentDegrees = TOTAL_DEGREES;
            }
            //一次移动角度超过300，就是滑动到了结束和开始的边界（逆时针）
            if (moveDegrees - mLastDegrees > 300){
                dragFlag = false;
                mCurrentDegrees = 0;
            }
        }else {
            //到达最大值后，上一次角度大于当前角度（即正在逆时针拖拽）
            if (mCurrentDegrees == TOTAL_DEGREES && (mLastDegrees - moveDegrees > 0)){
                double diff = TOTAL_DEGREES - moveDegrees;
                if(diff < 45 && diff > 0){
                    dragFlag = true;
                }
            }
            //到达最小值后，当前角度大于上一次角度（即正在顺时针拖拽）
            if (mCurrentDegrees == 0 && mLastDegrees - moveDegrees > 300){
                if(mLastDegrees - moveDegrees > 0){
                    dragFlag = true;
                }
            }
        }
        mLastDegrees = moveDegrees;
        Log.i("lzx", "mCurrentDegrees:" + mCurrentDegrees);
    }

    private boolean isInSwitchArea(float x, float y) {
//        //点击开关图标
//        return (switchRect.left - switchClickPadding <= x && x <= switchRect.right + switchClickPadding)
//                && (switchRect.top - switchClickPadding <= y && y <= switchRect.bottom + switchClickPadding);
        float centerX = getWidth() / 2;
        float centerY = getHeight() / 2;
        float clickDistance = (float) Math.sqrt(Math.pow(Math.abs(x - centerX), 2) + Math.pow(Math.abs(y - centerY), 2));
        return clickDistance < centerRadius;
    }

    private boolean isInArcArea(float x, float y) {
        double currentDegrees = getTouchAngle(x, y);
        //角度限制放宽5，优化触控体验
        return isInRingArea(x, y) && currentDegrees <= TOTAL_DEGREES + 5 && (currentDegrees >= 0 || currentDegrees < 355);
    }

    private boolean isInRingArea(float x, float y) {
        float centerX = getWidth() / 2;
        float centerY = getHeight() / 2;
        float distance = (float) Math.sqrt(Math.pow(Math.abs(centerX - x), 2) + Math.pow(Math.abs(centerY - y), 2));
        //点坐标在圆内，并且大于白色圆球最外侧(圆环内可拖动)
        return distance <= centerX - arcPadding && distance >= centerX - (arcPadding + mStrokeWidth + barRadius - mStrokeWidth / 2f);
    }

    private void calculateProgress() {
        mProgress = (float) (mCurrentDegrees / TOTAL_DEGREES);
        if (mProgress > 1) {
            mProgress = 1;
        }
        if (mProgress < 0) {
            mProgress = 0;
        }
    }

    /**
     * 获取触摸坐标的夹角度数
     *
     * @param x
     * @param y
     * @return
     */
    private float getTouchAngle(float x, float y) {
        int centerX = getWidth() / 2;
        int centerY = getHeight() / 2;
        //求触摸点弧形的夹角度数
        int angle = (int) (Math.atan2((centerY - y), (centerX - x)) * 180 / Math.PI + CALCULATE_START_DEGREES);
        while (angle < 0) {
            angle += 360;
        }
        return angle;
    }

    public void setOpenState(boolean openState) {
        if(isOpen == openState){
            return;
        }
//        if (openState) {
//            mTemp = preTemp;
//        } else {
//            preTemp = mTemp;
//        }
        isOpen = openState;
//        calculateProgressByTemp();
        invalidate();
    }

    public boolean isOpen() {
        return isOpen;
    }

    public float getTemp() {
        return mTemp;
    }

    public void setTemp(float temp) {
        if(temp == 0){
            tempIsNotSet = true;//未设置温度
        }else{
            tempIsNotSet = false;
        }
        if (temp < min) {
            temp = min;
        } else if (temp > max) {
            temp = max;
        }
        mTemp = temp;
        calculateProgressByTemp();
        invalidate();
    }

    private void calculateProgressByTemp(){
        float currentTemp = (int) (mProgress * tempTotalInterval) + min;
        //比较当前温度和设置的温度，一样就以当前百分比来绘制
        if(currentTemp != mTemp){
            mProgress = (mTemp - min) / tempTotalInterval;
        }
        mPerIntervalProgress = mProgress;
        mCurrentDegrees = mProgress *  TOTAL_DEGREES;
    }

    private OnChangeListener mOnChangeListener;

    public void setOnChangeListener(OnChangeListener mOnChangeListener) {
        this.mOnChangeListener = mOnChangeListener;
    }

    public interface OnChangeListener {
        void onValueChanged(float value);

        void onStopTrackingTouch(float value);

        void onSwitch(boolean isOpen);
    }

    private ValueAnimator.AnimatorUpdateListener mUpdateListener = new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            rotationDegree = (int) animation.getAnimatedValue();
            invalidate();
        }
    };

    ValueAnimator mAnimator = null;
    public void start() {
        if (mAnimator == null) {
            mAnimator = ValueAnimator.ofInt(0, 359);
            mAnimator.addUpdateListener(mUpdateListener);
            mAnimator.setDuration(1600);
            mAnimator.setRepeatMode(ValueAnimator.RESTART);
            mAnimator.setRepeatCount(ValueAnimator.INFINITE);
            mAnimator.setInterpolator(new LinearInterpolator());
            mAnimator.start();
        } else if (!mAnimator.isStarted()) {
            mAnimator.start();
        }
    }

    public void stop() {
        if (mAnimator != null) {
            mAnimator.removeUpdateListener(mUpdateListener);
            mAnimator.removeAllUpdateListeners();
            mAnimator.cancel();
            mAnimator = null;
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        start();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stop();
    }

    @Override
    protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == VISIBLE) {
            start();
        } else {
            stop();
        }
    }
}
